from calcWaitTime import CalcWaitTime

import threading
import time
class TpsThread(threading.Thread):
    def __init__(self, tps=1, interval=0.1, cb=None):
        super(TpsThread, self).__init__()
        self.__calc = CalcWaitTime(tps, 1, interval)
        self.__isRunning = False
        self.__cb = cb

    def cbStart(self):
        pass
    def cbEnd(self):
        pass
    def callback(self, curTransCnt):
        print("callback:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , curTransCnt)
        time.sleep(0.01)
        return True

    def stop(self):
        self.__isRunning = False

    def isRunning(self):
        return self.__isRunning

    def run(self):
        if self.__cb is None:
            self.__cb = self.callback

        self.cbStart()
        self.__isRunning = True
        while self.isRunning():
            self.__calc.workLoadStart()

            #print("before callback", str(self.__calc))
            curTransCnt = self.__calc.getCurrentTrans()
            if curTransCnt > 0:
                if False == self.__cb(curTransCnt):
                    print("Error: callback got False, thread exit")
                    break
                #end if
            #end if curTrans > 0

            #print("after callback", str(self.__calc))
            wait = self.__calc.workLoadEnd()
            if wait > 0:
                time.sleep(wait)
            #end if
        #end while
        self.cbEnd()
    #end def


def testTpsThread():
    def call(curTransCnt):
        print("call:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) , curTransCnt)
        time.sleep(0.01)
        return True
    t = TpsThread(100, 0.1, call)
    t.start()
    try:
        time.sleep(10)
    except KeyboardInterrupt:
        print("key interrupted")
    t.stop()


if __name__ == "__main__":
    testTpsThread()
